package com.lac.component.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lac.component.dao.GoodsSpuMapper;
import com.lac.component.model.GoodsSpu;
import com.lac.component.utils.OSSUrlUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;



/**
 * @author xiaokuixiao
 * date2025/7/30 16:14
 */
@RestController
@Slf4j
public class GoodsSpuController {
    @Autowired
    private GoodsSpuMapper goodsSpuMapper;



    @GetMapping("/picUrls")
    public String   goodsSpurPage() {
        StringBuffer combinedSql = new StringBuffer();
        List<GoodsSpu> goodsSpurPage = goodsSpuMapper.getGoodsSpurPage();
        StringBuffer deleteCombinedSql = new StringBuffer();
//        pageGoodsSpuTraceSources = pageGoodsSpuTraceSources.stream().limit(3).collect(Collectors.toList());
        List<String> idList = new ArrayList<>();
        List<String> serverNamesMutable = new ArrayList<>(Arrays.asList("wm-dev-b1", "wm-prod-b1", "em-dev-b1", "em-prod-b1","https://siwmstatic.ecej.com"));
        // 遍历所有需要处理的商品，或者只处理第一个/特定id的
        // 这里只是示例，通常你会有一个循环
        String url = "https://wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/video";
        String imageUrl = "https://wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/material";
        for (int i = 0; i < goodsSpurPage.size(); i++) {
            GoodsSpu goodsSpu = goodsSpurPage.get(i);;
            String Olddescription = goodsSpu.getDescription();
            String newdescription = checkAndReuploadResources(Olddescription, serverNamesMutable);
            String OldPicUrls = goodsSpu.getPicUrls() ;
            String newPicUrls = checkAndReuploadPicUrls(OldPicUrls, serverNamesMutable);

            // 比较新旧JSON字符串，避免不必要的更新
            if ((!newdescription.equals(Olddescription) || newdescription.contains(url)||newdescription.contains(imageUrl)) && (!newPicUrls.equals(OldPicUrls) || newPicUrls.contains(url)||newPicUrls.contains(imageUrl))) {
                String goodsSpuId = goodsSpu.getId().replace("'", "''"); // 简单的单引号转义

                String updateSql = String.format(
                        "UPDATE `oms_mall`.`goods_spu` SET `%s` = '%s' , `%s` = '%s' WHERE  `id` = '%s';",
                        "description", newdescription, "pic_urls", newPicUrls,
                        goodsSpuId
                );
                // 构建SQL更新语句
//                String updateSql = buildUpdateSql(goodsSpuChannel.getId(), newDraftJson, "draft_json");

                combinedSql.append(updateSql).append("\n");

                String deleteSql = buildDeleteSql(goodsSpu.getId());

                deleteCombinedSql.append(deleteSql).append("\n");
            }else if((!newdescription.equals(Olddescription) || newdescription.contains(url)||newdescription.contains(imageUrl)) && newPicUrls.equals(OldPicUrls)) {
                String updateSql = buildUpdateSql(goodsSpu.getId(), newdescription, "description");

                combinedSql.append(updateSql).append("\n");

                String deleteSql = buildDeleteSql(goodsSpu.getId());

                deleteCombinedSql.append(deleteSql).append("\n");
            }else if(newdescription.equals(Olddescription) && (!newPicUrls.equals(OldPicUrls)|| newPicUrls.contains(url)||newPicUrls.contains(imageUrl))) {
                String updateSql = buildUpdateSql(goodsSpu.getId(), newPicUrls, "pic_urls");

                combinedSql.append(updateSql).append("\n");

                String deleteSql = buildDeleteSql(goodsSpu.getId());

                deleteCombinedSql.append(deleteSql).append("\n");
            } else {
                idList.add(goodsSpu.getId());
                System.out.println("GoodsSpu ID: " + goodsSpu.getId() + " 的图片URL没有变化，无需更新。");
            }
            log.info("条数============================================={}", i+1);
        }
        log.info("combinedSql:{}", combinedSql);
        if (idList.size() > 0) {
            String goodsSpuId = String.join(",", idList);
            String selectSql = "SELECT * FROM `oms_mall`.`goods_spu` WHERE `id` IN (" + goodsSpuId + ");";
            String string = combinedSql.append(deleteCombinedSql).append(selectSql).toString();
            log.info("selectSql:{}", string);
            return string;
        } else {
            String string = combinedSql.append(deleteCombinedSql).toString();
            log.info("selectSql:{}",string);
            return string;
        }
    }


    public static String checkAndReuploadPicUrls(String picUrlsJson,  List<String> serverNames) {
        Gson gson = new Gson();
        Type listType = new TypeToken<List<String>>() {
        }.getType();
        List<String> urlList = null;
        try {
            urlList = gson.fromJson(picUrlsJson, listType);
        } catch (Exception e) {
            log.error(" picUrls JSON失败: {}, JSON: {}", e.getMessage(), picUrlsJson);
        }
        // 存储新生成的OSS URL
        List<String> ossUrls = new ArrayList<>();
        boolean hasAnyUrlUploaded = false; // 标记是否有任何一个URL成功上传
        if (urlList != null && !urlList.isEmpty()) { // 确保urlList不为null且不为空
            for (String picUrl : urlList) {
                String ossUrl = null;
                boolean isUploaded = false;
                for (String serverName : serverNames) {
                    if (picUrl.contains(serverName)) {
                        isUploaded = true;
                    }
                }
                if (StringUtils.isNotBlank(picUrl) && !isUploaded) {
                    try {
                        ossUrl = OSSUrlUploader.uploadFromUrlWithSnowflakeName(picUrl, "common/material");
                        if (StringUtils.isNotBlank(ossUrl)) {
                            ossUrls.add(ossUrl);
                            hasAnyUrlUploaded = true;
                        } else {
                            // 如果上传返回空，保留原URL以防止数据丢失，或者记录错误
                            log.warn("图片 {} 上传到OSS返回空URL，将保留原URL。", picUrl);
                            ossUrls.add(picUrl); // 保持原有的URL
                        }
                    } catch (Exception e) {
                        log.error("上传图片异常{},原始URL:{},错误信息:{}", e.getClass().getSimpleName(), picUrl, e.getMessage());
                        // 如果上传失败，保留原始URL，避免数据丢失
                        ossUrls.add(picUrl);
                    }
                } else {
                    // 如果原始URL是空白的，也加入到新列表中，保持数组结构
                    ossUrls.add(picUrl);
                }
            }
        }
        // 只有当有图片成功上传或列表结构发生变化时才更新
        // 确保即使所有上传都失败，但是原始picUrls存在，我们也会生成一个新的JSON字符串 (可能包含原始URL)
        String newPicUrlsJson = gson.toJson(ossUrls);
        return newPicUrlsJson;
    }

    /**
     * 检查并重新上传图片到OSS
     * @param htmldescription 包含图片URL的HTML内容
     * @param serverNames 需要重新上传的服务器名称列表
     * @return 更新后的HTML内容
     */
    /**
     * 检查并重新上传图片到OSS
     * @param htmldescription 包含图片URL的HTML内容
     * @param serverNames 需要重新上传的服务器名称列表
     * @return 更新后的HTML内容
     */
    public static String checkAndReuploadResources(String htmldescription, List<String> serverNames) {
        if (StringUtils.isBlank(htmldescription)) {
            return htmldescription;
        }

        // 同时匹配a标签的href、img/video标签的src
        String regex = "<(a|img|video)[^>]+?\\b(href|src)\\s*=\\s*[\"']?([^\"'\\s>]+)[\"']?";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(htmldescription);
        StringBuffer result = new StringBuffer();
        String url = "https://wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/video";
        String imageUrl = "https://wm-prod-b1.oss-cn-beijing.aliyuncs.com/common/material";

        while (matcher.find()) {
            String fullTag = matcher.group(0);   // 完整标签
            String tagType = matcher.group(1);   // 标签类型 (a/img/video)
            String attrType = matcher.group(2);  // 属性类型 (href/src)
            String resourceUrl = matcher.group(3); // 资源URL

            log.info("处理{}标签的{}属性: {}, URL: {}", tagType, attrType, fullTag, resourceUrl);

            // 检查是否需要重新上传
            boolean needReupload = false;
            for (String serverName : serverNames) {
                if (resourceUrl.contains(serverName)) {
                    log.info("URL 包含 serverName {}, 不重新上传", serverName);
                    needReupload = true;
                    break;
                }
            }

            String newResourceUrl = resourceUrl;
            if (!needReupload && StringUtils.isNotBlank(resourceUrl) && resourceUrl.startsWith("http")) {
                try {
                    // 根据标签类型决定上传目录
                    String uploadPath;
                    if ("a".equals(tagType)) {
                        uploadPath = "common/material"; // a标签按图片处理
                    } else {
                        uploadPath = "img".equals(tagType)
                                ? "common/material"
                                : "common/video";
                    }
                    newResourceUrl = OSSUrlUploader.uploadFromUrlWithSnowflakeName(resourceUrl, uploadPath);
                } catch (Exception e) {
                    log.error("重新上传{}失败: {}", tagType, resourceUrl, e);
                }
            } else {
                log.info("跳过处理: needReupload={}, isHttp={}", needReupload, resourceUrl.startsWith("http"));
            }

            // 替换属性值并保留原标签结构
            String newTag = fullTag.replace(attrType + "=" + (fullTag.contains("\"") ? "\"" : "'") + resourceUrl,
                    attrType + "=\"" + newResourceUrl + "\"");
            matcher.appendReplacement(result, Matcher.quoteReplacement(newTag));
            log.info("替换后的标签：{}", newTag);
        }
        matcher.appendTail(result);
        return result.toString();
    }


    /**
     * 构建SQL UPDATE语句的辅助方法
     * @param goodsSpuId 商品ID
     * @param newPicUrlsJson 新的图片URL JSON字符串
     * @return SQL UPDATE语句
     */
    private String buildUpdateSql(String  goodsSpuId, String newPicUrlsJson ,String featureName) {
        // 注意：实际生产环境中，请使用PreparedStatement防止SQL注入！
        // 这里的拼接仅用于演示生成的SQL字符串。

        // 为了SQL安全，需要对newPicUrlsJson进行适当的转义，特别是单引号
        // 通常数据库驱动或ORM框架会自动处理
        String escapedNewPicUrlsJson = newPicUrlsJson.replace("'", "''"); // 简单的单引号转义
        goodsSpuId = goodsSpuId.replace("'", "''"); // 简单的单引号转义

        return String.format(
                "UPDATE `oms_mall`.`goods_spu` SET `%s` = '%s' WHERE `id` = '%s';",
                featureName, escapedNewPicUrlsJson,
                goodsSpuId
        );
    }

    /**
     * 构建SQL DELETE语句的辅助方法
     * @param goodsSpuId 商品ID
     * @return SQL DELETE语句
     */
    private String buildDeleteSql(String  goodsSpuId) {
        return String.format("DELETE FROM `oms_mall`.`goods_spu` WHERE `id` = %s;","'"+goodsSpuId+"'");
    }
}
